package reBuildBinaryTree;

import java.util.Arrays;
import java.util.Objects;

public class Solution2 {
    public static void main(String[] args) {
        int[] pre = {1,2,3,4,5,6,7};
        int[] mid = {3,2,4,1,6,5,7};
        Solution2 solution2 = new Solution2();
//        TreeNode head = solution2.reConstructBinaryTree(pre,mid);
        Main main = new Main();
        TreeNode head = solution2.reConstructBinaryTree(new int[]{1,2,4,7,3,5,6,8} , new int[]{4,7,2,1,5,3,8,6});
        main.frontForTree(head);
    }
    public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
        if(Objects.isNull(vin) || 0 == vin.length){
            return null ;
        }
        int rootNodeIndex = locateIndex(vin[0],pre)  ;
        int temp = 0 ;
        int right_vin[] = null ;
        int left_vin[] = null ;

        for(int v : vin){
            temp = locateIndex(v,pre);
            if(temp<rootNodeIndex){
                rootNodeIndex = temp ;
            }
        }
        TreeNode root = new TreeNode(pre[rootNodeIndex]);
        if(vin.length==1){
            return root ;
        }
        int splitPoint = locateIndex(pre[rootNodeIndex] , vin);
        right_vin = Arrays.copyOfRange( vin , splitPoint + 1 , vin.length);
        left_vin = Arrays.copyOfRange(vin ,0 , splitPoint );
        root.setLeft(reConstructBinaryTree(pre , left_vin));
        root.setRight(reConstructBinaryTree(pre , right_vin));
        return root;
    }
    private int locateIndex(int target , int[]  array){
        for(int i = 0 ; i < array.length ; i++){
            if(array[i] == target){
                return i ;
            }
        }
        return -1 ;
    }
}
